/*
 * Copyright 2020 Baheal
 * @(#)ByyyOAUtils.java
 */
package com.byyy.ccts.core.utils.byyyoa;

import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.core.utils.CacheUtils;
import com.byyy.ccts.core.utils.SpringContextHolder;
import com.byyy.ccts.core.utils.StringUtils;
import com.byyy.ccts.core.utils.http.HttpUtils;
import com.byyy.ccts.modules.cc.Global;
import com.byyy.ccts.modules.sys.entity.Dict;
import com.byyy.ccts.modules.sys.entity.TZParam;
import com.byyy.ccts.modules.sys.service.IDictService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * Created by DELL on 2020-7-17.
 */
public class OAUtils implements ILogBase {

    /**
     * 通用邮件列表
     * @param model
     */
    public static void sendMail(OAModel model) {
        sendMail(model.getCode(), model.getTitle(), model.getContent(), "N");
    }

    /**
     * 通用邮件列表
     * @param code
     */
    public static boolean sendMail(String code, String title, String content, String smsFlg) {
        // 获取邮件发送人列表
        IDictService dictService = SpringContextHolder.getBean(IDictService.class);
        List<Dict> mailSendTo = dictService.selectDictUsedListByGCode(code, null);

        if (mailSendTo == null || mailSendTo.size() < 1) {
            logger.error("邮件发送人为空！");
            return false;
        }
        StringBuilder sendTo = new StringBuilder();
        for (Dict temp : mailSendTo) {
            sendTo.append(temp.getValue()).append(";");
        }

        return sendMailTo(sendTo.toString(), title, content, smsFlg);

    }

    /**
     * 通用邮件列表
     * @param sendTo
     */
    public static boolean sendMailTo(String sendTo, String title, String content, String smsFlg) {
        // 获取token
        String token = (String) CacheUtils.get("oa.token");
        if (StringUtils.isEmpty(token)) {
            token = getOAToken();
        }

        // 发送邮件,发送失败的情况，重新获取token，下次再发送
        if (!OAUtils.sendOAMail(content, token, sendTo.toString(), title, smsFlg)) {
            return OAUtils.sendOAMail(content, getOAToken(), sendTo.toString(), title, smsFlg);
        }

        return true;
    }

    /**
     * 获取发送邮件的Token
     * @return
     */
    public static String getOAToken() {
        String token = null;
        String ret = null;
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        try {
            ret = HttpUtils.postWithJson(Global.OA_TOKEN_URL, Global.OA_TOKEN_USER,
                    new HashMap<String, String>() {{
                        put("Authorization", "Basic " + Global.OA_TOKEN_AUTH);
                    }});

            if (StringUtils.isNotEmpty(ret)) {
                rootNode = mapper.readTree(ret);
                token = rootNode.path("token").textValue();
                CacheUtils.put("oa.token", token);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        return token;
    }

    /**
     * 发送OA邮件
     * @param content
     * @param token
     * @return
     */
    public static boolean sendOAMail(String content, final String token, String sendTo, String caption, String smsFlg) {
        logger.debug("开始发送OA邮件");
        OAUserMail oaUserMail = generateUserMail(content, sendTo, caption, smsFlg);
        String ret = null;
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        try {
            ret = HttpUtils.postWithJson(Global.OA_MAIL_WX_URL, mapper.writeValueAsString(oaUserMail),
                    new HashMap<String, String>() {{
                        put("DF_KEY", token);
                    }});
            logger.debug("OA发送结果：" + ret);
            if (StringUtils.isEmpty(ret)) {
                return false;
            }
            // 如果发送失败，可能是因为token失效，这时候可以重新获取token再发送
            rootNode = mapper.readTree(ret);
            if (!"SUCCESS".equals(rootNode.path("code").textValue())) {
                return false;
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        logger.debug("OA邮件发送完毕");
        return true;
    }

    /**
     * 生成消息实体
     * @param content
     * @return
     */
    private static OAUserMail generateUserMail(String content, String sendTo, String caption, String smsFlg) {
        OAUserMail oaUserMail = new OAUserMail();
        oaUserMail.setSend_man(sendTo);
        oaUserMail.setCaption(caption);
        oaUserMail.setMail_contents(content);
        oaUserMail.setTel_awake(smsFlg);
        return oaUserMail;
    }

}
